<template>
    <div class="front">
        <el-form :model="searchForm" label-width="120px">
            <el-form-item class="input" label="租户名称">
                <el-input v-model="searchForm.name" />
            </el-form-item>
            <el-form-item class="input" label="手机号">
                <el-input v-model="searchForm.name" />
            </el-form-item>
        </el-form>
        <el-button class="search" type="primary">查询</el-button>
    </div>

    <div class="tail">
        <div class="tail-action">
            <el-button type="primary" @click="openAdd()">新增租户</el-button>
        </div>
        <el-table :data="tableData()" border style="width: 100%">
            <el-table-column type="selection" width="40" />
            <el-table-column prop="tenantCode" label="租户编码" min-width="90" />
            <el-table-column prop="tenantName" label="租户名称" min-width="150" />
            <el-table-column prop="tenantSource" label="租户来源" min-width="100"/>
            <el-table-column prop="statusName" label="租户状态" min-width="120"/>
            <el-table-column prop="createTime" label="注册时间" min-width="160" />
            <el-table-column prop="tenantRegisterIp" label="注册来源IP地址" min-width="150" />
            <el-table-column prop="phonenumber" label="注册手机号码" min-width="150" />
            <el-table-column prop="email" label="租户邮箱" min-width="200" />
            <el-table-column prop="tenantLocation" label="租户所在地" min-width="100" />
            <el-table-column prop="tenantPackage" label="套餐情况" min-width="100" />
            <el-table-column prop="tenantExpireDate" label="套餐到期时间" min-width="160" />
            <el-table-column prop="tenantStorageSpaceTotal" label="租户套餐容量"  />
            <el-table-column prop="tenantStorageSpaceUsed" label="租户套餐现容量情况" min-width="100" />
            <el-table-column prop="tenantContactPersonName" label="租户联系人姓名" min-width="150" />
            <el-table-column prop="tenantContactPersonPhone" label="租户联系人联系方式" min-width="150" />
            <el-table-column prop="salesPersonName" label="跟进人" min-width="100" />
            <el-table-column prop="salesStatus" label="跟进人状态" min-width="100">
                <template #default="scope">
                    <p v-if="scope.row.salesStatus == 1">在职</p>
                    <p v-else>离职</p>
                </template>
            </el-table-column>
            <el-table-column prop="employeeId" label="跟进人工号" min-width="100"/>
            <el-table-column prop="remark" label="备注" min-width="100" />
            <el-table-column fixed="right" label="操作" width="60px">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="openEdit(scope.row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
                layout="prev, pager, next ,total,sizes" :total="data.total" @current-change="handleCurrentChange"
                @size-change="handleSizeChange" />
        </div>
    </div>

    <div class="dialog-list">
        <el-dialog v-model="dialogVisible1" title="新增租户" width="35%" :show-close="false" :close-on-click-modal="true"
            @close="handleClose">
            <div>
                <el-form :model="tenantForm" label-width="160px" :rules="tenantRules" ref="tenantRef">
                    <el-form-item label="租户编码" prop="tenantCode" :required="true">
                        <el-input v-model="tenantForm.tenantCode" placeholder="请输入租户编码" disabled />
                    </el-form-item>
                    <el-form-item label="租户名称" prop="tenantName" :required="true">
                        <el-input v-model="tenantForm.tenantName" placeholder="请输入租户公司名称" />
                    </el-form-item>
                    <el-form-item label="注册手机号码" prop="phonenumber" :required="true">
                        <el-input v-model="tenantForm.phonenumber" placeholder="请输入手机号码" />
                    </el-form-item>
                    <el-form-item label="租户邮箱">
                        <el-input v-model="tenantForm.email" placeholder="请输入租户邮箱" />
                    </el-form-item>
                    <el-form-item label="租户来源" prop="tenantSource">
                        <el-select v-model="tenantForm.tenantSource" placeholder="请选择">
                            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"
                                placeholder="请输入租户来源">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="租户所在地">
                        <el-input v-model="tenantForm.tenantLocation" placeholder="请输入联系地址" />
                    </el-form-item>
                    <el-form-item label="租户套餐容量" prop="tenantStorageSpaceTotal" :required="true">
                        <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="tenantForm.tenantStorageSpaceTotal"
                            placeholder="请输入租户套餐容量" style="width: 200px;">
                            <template v-slot:append>GB</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="套餐情况" :required="true">
                        <el-input v-model="tenantForm.tenantPackage" placeholder="请输入套餐情况" />
                    </el-form-item>
                    <el-form-item label="套餐到期时间" prop="tenantExpireDate">
                        <el-date-picker v-model="tenantForm.tenantExpireDate" type="datetime" placeholder="请输入有效期限" />
                    </el-form-item>
                    <el-form-item label="租户联系人姓名" prop="tenantContactPersonName" :required="true">
                        <el-input v-model="tenantForm.tenantContactPersonName" placeholder="请输入租户联系人姓名" />
                    </el-form-item>
                    <el-form-item label="租户联系人联系方式" prop="tenantContactPersonPhone" :required="true">
                        <el-input v-model="tenantForm.tenantContactPersonPhone" placeholder="请输入租户联系人联系方式" />
                    </el-form-item>
                    <el-form-item label="跟进人" prop="salesPersonName" :required="true">
                        <el-select v-model="tenantForm.salesPersonName" placeholder="请选择">
                            <el-option v-for="item in adminUserList" :label="item.nickName" :value="item.nickName"
                                placeholder="请选择跟进人">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="跟进人状态" >
                        <el-select v-model="tenantForm.salesStatus" placeholder="请选择">
                            <el-option v-for="item in saleType" :label="item.label" :value="item.value"
                                placeholder="请选择跟进人状态">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="跟进人工号" >
                        <el-input v-model="tenantForm.employeeId" placeholder="请输入跟进人工号" />
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="tenantForm.remark" placeholder="请输入内容" />
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible1 = false">取消</el-button>
                    <el-button type="primary" @click="handleAddTenant">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog v-model="dialogVisible2" title="编辑租户" width="30%" :show-close="false" @close="handleClose">
            <div>
                <el-form :model="tenantForm" label-width="160px" ref="tenantRef">
                    <el-form-item label="租户名称" prop="tenantCode" :required="true">
                        <el-input v-model="tenantForm.tenantCode" placeholder="请输入租户编码" disabled />
                    </el-form-item>
                    <el-form-item label="租户公司名称" prop="tenantName" :required="true">
                        <el-input v-model="tenantForm.tenantName" placeholder="请输入租户公司名称" />
                    </el-form-item>
                    <el-form-item label="注册手机号码" prop="phonenumber" :required="true">
                        <el-input v-model="tenantForm.phonenumber" placeholder="请输入手机号码" />
                    </el-form-item>
                    <el-form-item label="租户邮箱">
                        <el-input v-model="tenantForm.email" placeholder="请输入租户邮箱" />
                    </el-form-item>
                    <el-form-item label="租户来源" prop="tenantSource">
                        <el-select v-model="tenantForm.tenantSource" placeholder="请选择">
                            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"
                                placeholder="请输入租户来源">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="租户所在地">
                        <el-input v-model="tenantForm.tenantLocation" placeholder="请输入联系地址" />
                    </el-form-item>
                    <el-form-item label="租户套餐容量" prop="tenantStorageSpaceTotal" :required="true">
                        <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="tenantForm.tenantStorageSpaceTotal"
                            placeholder="请输入租户套餐容量" style="width: 200px;">
                            <template v-slot:append>GB</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="套餐情况" :required="true">
                        <el-input v-model="tenantForm.tenantPackage" placeholder="请输入套餐情况" />
                    </el-form-item>
                    <el-form-item label="套餐到期时间" prop="tenantExpireDate">
                        <el-date-picker v-model="tenantForm.tenantExpireDate" type="datetime" placeholder="请输入有效期限" />
                    </el-form-item>
                    <el-form-item label="租户联系人姓名" prop="tenantContactPersonName" :required="true">
                        <el-input v-model="tenantForm.tenantContactPersonName" placeholder="请输入租户联系人姓名" />
                    </el-form-item>
                    <el-form-item label="租户联系人联系方式" prop="tenantContactPersonPhone" :required="true">
                        <el-input v-model="tenantForm.tenantContactPersonPhone" placeholder="请输入租户联系人联系方式" />
                    </el-form-item>
                    <el-form-item label="跟进人">
                        <el-select v-model="tenantForm.salesPersonName" placeholder="请选择">
                            <el-option v-for="item in adminUserList" :label="item.nickName" :value="item.nickName"
                                placeholder="请选择跟进人">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="跟进人状态" >
                        <el-select v-model="tenantForm.salesStatus" placeholder="请选择">
                            <el-option v-for="item in saleType" :label="item.label" :value="item.value"
                                placeholder="请选择跟进人状态">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="跟进人工号" >
                        <el-input v-model="tenantForm.employeeId" placeholder="请输入跟进人工号" />
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="tenantForm.remark" placeholder="请输入内容" />
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible2 = false">取消</el-button>
                    <el-button type="primary" @click="handleUpdateTenant">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
         
<script >
import { ref, defineComponent, reactive, toRefs, } from "vue";
import { ElMessageBox, ElMessage, } from 'element-plus'
import { addTenant, deleteTenant, getTenantList, updateTenant, getTenantCode, getAdminUsers } from '@/api/auth/auth'
import { onMounted } from "vue";

export default defineComponent({
    name: "TenantRole",
    components: {},

    setup() {
        const options = [{
            value: '1',
            label: '注册'
        }, {
            value: '2',
            label: '销售'
        }]
        const saleType = [{
            value: '0',
            label: '离职'
        }, {
            value: '1',
            label: '在职'
        }]
        //表格的全数据（这里是自定义的列表，要看分页效果自行往此数组内加数据）
        let tenantData = reactive({
            data: []
        });
        const searchForm = reactive({
            name: '',

        });
        const tenantForm = reactive({
            id: '',
            tenantCode: '',
            tenantName: '',
            phonenumber: '',
            adminId: '',
            email: '',
            status: 1,
            tenantSource: '',
            tenantPackage: 1,
            tenantLocation: '',
            tenantExpireDate: '',
            tenantStorageSpaceTotal: 30,
            remark: '',
            salesPersonId: '',
            salesPersonName: '',
            employeeId: '',
            salesStatus: '',
            tenantContactPersonName: '',
            tenantContactPersonPhone: '',
        });
        const tenantRules = reactive({
            tenantName: [{ required: true, message: '请输入内容', trigger: 'blur' },
            { min: 2, max: 10, message: '名称长度 在 2 到 10长度之间', trigger: 'blur' }],
            tenantContactPersonName: [{ required: true, message: '请输入内容', trigger: 'blur' },
            { min: 2, max: 10, message: '名称长度 在 2 到 10长度之间', trigger: 'blur' }],
            salesPersonId: [{ required: true, message: '请选择跟进人', trigger: 'change' },],
            tenantExpireDate: [{ type: 'date', required: true, message: '请选择套餐到期时间', trigger: 'blur' },
            {
                validator: (rule, value, callback) => {
                    const currentDate = new Date();
                    if (value && value > currentDate) {
                        callback();
                    } else {
                        callback(new Error('时间不能早于当前时间'));
                    }
                },
                trigger: 'blur',
            },],
            tenantStorageSpaceTotal: [{ required: true, message: '请输入正确的数字', trigger: 'blur' },
            {
                validator: (rule, value, callback) => {
                    if (value >= 1 && value <= 100) {
                        callback();
                    } else {
                        callback(new Error('限制容量必须在1到100之间'));
                    }
                },
                trigger: 'blur',
            }],
            phonenumber: [{ required: true, message: '请输入内容', trigger: 'blur' }, {
                type: 'number',
                message: '手机号格式不正确',
                trigger: 'blur',
                transform(value) {
                    var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/
                    if (!phonereg.test(value)) {
                        return false
                    } else {
                        return Number(value)
                    }
                }
            }],
            tenantContactPersonPhone: [{ required: true, message: '请输入内容', trigger: 'blur' }, {
                type: 'number',
                message: '手机号格式不正确',
                trigger: 'blur',
                transform(value) {
                    var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/
                    if (!phonereg.test(value)) {
                        return false
                    } else {
                        return Number(value)
                    }
                }
            }],
            
        });
        const adminUserList = ref([])
        const tenantRef = ref(null)
        let dialogVisible1 = ref(false)
        const dialogVisible2 = ref(false)
        //表格用到的参数
        let state = reactive({
            data: {
                page: 1,
                limit: 10,
                total: tenantData.data.length,
            }
        });
        onMounted(() => {
            handleGetTenantList(state.data.page, state.data.limit)
            getTenantCode().then((res) => {
                tenantForm.tenantCode = res
            })
            getAdminUsers().then(res => {
                adminUserList.value = res.salesPersonList
            })
        })

        //前端限制分页（tableData为当前展示页表格）
        const tableData = () => {
          
            return tenantData.data
        };
        //改变页码
        const handleCurrentChange = (e) => {
            state.page = e;
            handleGetTenantList(e, state.data.limit)
        };
        //改变页数限制
        const handleSizeChange = (e) => {
            state.limit = e;
            handleGetTenantList(state.data.page, e)
        };
        const dateTurn = (dateTime) => {//时间格式转换
            const date = new Date(dateTime);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            return formattedDate
        }
        const handleGetTenantList = (page, limit) => {
            getTenantList(page, limit).then((res) => {
                let list = res.rows
            let currentDateTime = new Date().getTime()
            for(let i in list){
                let startTime = new Date(list[i].tenantExpireDate).getTime()
                if(startTime - currentDateTime>3 * 24 * 60 * 60 * 1000){
                    list[i].statusName = '使用中'
                }else if(startTime - currentDateTime>0 * 24 * 60 * 60 * 1000){
                    list[i].statusName = '临近到期'
                }else {
                    list[i].statusName = '未续费' + '('+(- Math.trunc((startTime - currentDateTime) / (24 * 60 * 60 * 1000))
                    )+'天)'
                }
            }
                tenantData.data = list
                state.data.total = res.total
            })
        }
        //添加租户
        const handleAddTenant = () => {
            tenantRef.value.validate().then(() => {//验证通过
                ElMessageBox.confirm('确认提交?')
                    .then(() => {
                        tenantForm.tenantExpireDate = dateTurn(tenantForm.tenantExpireDate)
                        addTenant(tenantForm).then((res) => {
                            res.code == 200 ? ElMessage.success('修改成功') : ElMessage.error(res.msg)
                            dialogVisible1.value = false
                            handleGetTenantList(state.data.page, state.data.limit)
                        })
                    })
                    .catch(() => {// catch error
                    })
            }).catch(() => {// catch error
            })
        }
        const handleUpdateTenant = () => {  //修改租户
            tenantRef.value.validate().then(() => {//验证通过
                ElMessageBox.confirm('确认提交?')
                    .then(() => {
                        tenantForm.tenantExpireDate = dateTurn(tenantForm.tenantExpireDate)
                        updateTenant(tenantForm).then((res) => {
                            res.code == 200 ? ElMessage.success('修改成功') : ElMessage.error(res.msg)
                            dialogVisible2.value = false
                            handleGetTenantList(state.data.page, state.data.limit)
                        })
                    })
                    .catch(() => {// catch error
                    })
            }).catch(() => { })
        }
        const openAdd = () => {
            dialogVisible1.value = true
            getTenantCode().then((res) => {
                tenantForm.tenantCode = res
            })
        }
        const openEdit = (data) => {
            dialogVisible2.value = true
            Object.keys(data).forEach(key => {
                tenantForm[key] = data[key];
            });
        }

        const handleDeleteTenant = (tenantId) => {        //删除租户
            ElMessageBox.confirm(
                '是否要删除该租户?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    deleteTenant(tenantId).then(() => {
                        handleGetTenantList(state.data.page, state.data.limit)
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                    })
                }).catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消操作',
                    })
                })
        }

        const handleClose = (formRef) => { //对话框关闭回调
            clearForm()
        }
        const clearForm = () => { //clearForm失效
            Object.keys(tenantForm).forEach(key => {
                tenantForm[key] = '';
            });
        }
        return {
            tenantData, options, adminUserList,saleType,
            dialogVisible1, tenantRef,
            dialogVisible2,
            searchForm,
            tenantForm,
            tenantRules,
            tableData, handleClose,
            handleCurrentChange, openEdit, openAdd,
            handleSizeChange,
            handleDeleteTenant, handleAddTenant, handleGetTenantList, handleUpdateTenant,
            ...toRefs(state),
        };
    },
});
</script>
        
<style rel="stylesheet/scss" lang="scss" scoped>
.front {
    background-color: #fff;
    padding: 10px;
    display: flex;

    .input {
        float: left;
    }

    .search {
        margin-left: 50px;
    }
}

.center {
    margin: 10px;
}

.tail {
    background-color: #fff;
    margin-top: 40px;
    padding: 10px;

    .tail-action {
        margin-bottom: 10px;
        display: flex;
    }
}
</style>